import requests
import logging
from django.conf import settings

logger = logging.getLogger(__name__)


class AmapService:
    """高德地图 API 工具类"""
    API_KEY = settings.AMAP_API_KEY  # 从 settings.py 读取 API Key
    GEOCODE_URL = "https://restapi.amap.com/v3/geocode/geo"  # 地理编码接口
    DISTANCE_URL = "https://restapi.amap.com/v3/distance"  # 距离计算接口

    @classmethod
    def geocode(cls, address):
        """地址转经纬度"""
        try:
            params = {
                "address": address.strip(),
                "key": cls.API_KEY,
                "output": "json"
            }
            response = requests.get(cls.GEOCODE_URL, params=params, timeout=10)
            result = response.json()

            if result.get("status") == "1" and len(result.get("geocodes", [])) > 0:
                location = result["geocodes"][0]["location"]  # 格式："lng,lat"
                lng, lat = location.split(",")
                return {"lng": float(lng), "lat": float(lat)}
            else:
                logger.error(f"地址转经纬度失败：address={address}, result={result}")
                return None
        except Exception as e:
            logger.error(f"地址转经纬度异常：address={address}, error={str(e)}")
            return None

    @classmethod
    def calculate_distance(cls, origin_lng, origin_lat, dest_lng, dest_lat):
        """计算两点直线距离（单位：米）"""
        try:
            params = {
                "origins": f"{origin_lng},{origin_lat}",  # 起点经纬度
                "destinations": f"{dest_lng},{dest_lat}",  # 终点经纬度
                "key": cls.API_KEY,
                "output": "json",
                "type": "1"  # 1=直线距离
            }
            response = requests.get(cls.DISTANCE_URL, params=params, timeout=10)
            result = response.json()

            if result.get("status") == "1" and len(result.get("results", [])) > 0:
                distance = int(result["results"][0]["distance"])
                return distance
            else:
                logger.error(
                    f"距离计算失败：origin=({origin_lng},{origin_lat}), dest=({dest_lng},{dest_lat}), result={result}")
                return None
        except Exception as e:
            logger.error(f"距离计算异常：error={str(e)}")
            return None